package com.access.boot.starter.sample.web;

import com.access.boot.apisdk.Result;
import com.access.boot.starter.sample.openapi.model.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提供Openapi
 *
 * @author Yangzhen
 * @date 2023/1/16 09:56
 * @since 1.0.0
 */
@RestController
@RequestMapping("openapi")
@Slf4j
public class OpenapiController {

    private static final Map<String, List<UserVO>> USER_MAP = new HashMap<>();

    static {
        USER_MAP.put("001", Arrays.asList(new UserVO("100", "张三", 18), new UserVO("101", "赵四", 19)));
        USER_MAP.put("002", Arrays.asList(new UserVO("102", "王五", 16)));
    }

    /**
     * 列表
     * 如果没有token的请求头，直接返回错误消息
     *
     * @param groupId
     * @param request
     * @return
     */
    @GetMapping("/{group_id}/users")
    public Object getList(@PathVariable("group_id") String groupId, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            Result result = new Result<>();
            result.setMsg("没有Token参数");
            result.setCode(1);
            return result;
        }

        Result<List<UserVO>> userVOResult = new Result<>();
        List<UserVO> userVOS = USER_MAP.get(groupId);
        userVOResult.setCode(0);
        userVOResult.setData(userVOS);
        return userVOResult;
    }

    /**
     * 查询
     * 如果没有token的请求头，直接返回错误消息
     *
     * @param groupId
     * @param userId
     * @param request
     * @return
     */
    @GetMapping("/{group_id}/user")
    public Object getList(@PathVariable("group_id") String groupId, @RequestParam("user_id") String userId, HttpServletRequest request) {

        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            Result result = new Result<>();
            result.setMsg("没有Token参数");
            result.setCode(1);
            return result;
        }

        Result<UserVO> userVOResult = new Result<>();
        List<UserVO> userVOS = USER_MAP.get(groupId);

        for (UserVO userVO : userVOS) {
            if (userVO.getId().equals(userId)) {
                userVOResult.setData(userVO);
                break;
            }
        }
        userVOResult.setCode(0);
        return userVOResult;
    }
}
